<template>
	<view data-clipboard-action="cut" data-clipboard-target="#bar" class="item_content">
		<view style="display: flex;justify-content: space-between;align-items: flex-start">
			<uv-text v-if="item.title" :text="replaced(item.title)" class="selectable-text" :mode="'text'"
				customStyle="margin: 5px 0px;width:100%" align="top" @click="copy(item.title)"></uv-text>
			<uv-text v-if="item.role=='user'"
				:text="replaced(item.content||item.text||item.revised_prompt||item.prompt||item.userPrompt||(item.musics && item.musics[0].title))"
				class="selectable-text" :mode="'text'" customStyle="margin: 5px 0px;width:100%" align="top"
				@click="copy(item.content)"></uv-text>
			<rich-text v-else @click="copyCode" class="selectable-text" style="font-size: 14px;margin-bottom: 3px;"
				:nodes="replaced((item.data && item.data[0].revised_prompt)||item.content||item.text||item.revised_prompt||item.prompt||item.userPrompt||(item.musics && item.musics[0].title))"
				@tap="copyCode"></rich-text>
			<!-- <mp-html :content="replaced((item.data && item.data[0].revised_prompt)||item.content||item.text||item.revised_prompt||item.prompt||item.userPrompt||(item.musics && item.musics[0].title))" /> -->
			<el-link v-if="item.musics||item.videoUrl"
				style="width: 70px;font-size: 12px; color:#8E949C;display: flex;justify-content: flex-end;align-items: center;"
				@click="musicShow = !musicShow">
				<i style="margin-right: 3px;" class="el-icon-view"></i>
				{{musicShow?'隐藏':'查看更多'}}
			</el-link>
		</view>
		<view v-if="item.content && item.content[0].text">
			<view v-for="(ite,ind) in item.content" :key="ind">
				<el-image v-if="ite.image_url&&ite.image_url.url" style="max-width:250px; height: auto;"
					:src="ite.image_url.url+saveImg" fit="fill" :preview-src-list="[ite.image_url.url]"></el-image>
			</view>
		</view>

		<view v-if="item.musics" style="display: flex;justify-content: flex-start;align-items: center;flex-wrap: wrap;">
			<view v-if="item.musics[0]" v-for="(ite,ind) in item.musics" :key="ind"
				style="margin-bottom: 10px;width: 230px;">
				<uv-swiper style="width: 98%;margin-bottom:5px ;" height="400"
					:list="[{url:ite.videoUrl||ite.audioUrl,type: 'video',poster:ite.imageUrl}]" keyName="url"
					:autoplay="false"></uv-swiper>
				<el-tooltip class="item" effect="dark" :content="tooltip" placement="top-start">
					<el-link
						style="font-size: 14px; color:#8E949C;margin-right: 10px;display: flex;justify-content: flex-start;align-items: center;"
						@click="download(ite.videoUrl||ite.audioUrl)">
						<i style="margin-right: 3px;" class="el-icon-download"></i>
						下载
					</el-link>
				</el-tooltip>
				<view v-if="musicShow" style="width: 98%;height: auto;border-radius: 5px;margin-top: 5px;">
					<el-image v-if="ite.imageUrl" style="width:100%; height: auto;padding: 0px;margin: 0px;"
						:src="ite.imageUrl+saveImg" fit="fill" :preview-src-list="[ite.imageUrl]">
						<div slot="error" class="image-slot">
							<el-image v-if="ite.imageLargeUrl" style="max-width:100%; height: auto;"
								:src="ite.imageLargeUrl+saveImg" fit="fill"
								:preview-src-list="[ite.imageLargeUrl]"></el-image>
						</div>
					</el-image>
					<rich-text @click="copyCode" class="selectable-text" selectable :nodes="replaced(ite.title)"
						@tap="copyCode"></rich-text>
					<rich-text style="font-size:12px;margin: 0px;padding: 0px;" @click="copyCode"
						class="selectable-text" selectable :nodes="replaced(ite.prompt)" @tap="copyCode"></rich-text>
				</view>
			</view>
		</view>

		<view v-if="item.videoFirstFrame&&item.videoLastFrame">
			<view v-if="item.videoUrl &&adjustColumn"
				:style="'width: 100%;height:'+Math.ceil((adjustColumn.width)/item.width*item.height)+'px'">
				<uv-swiper style="width: 100%;" :height="Math.ceil((adjustColumn.width)/item.width*item.height)"
					:list="[{url:item.videoUrl||item.audioUrl,type: 'video',poster:item.videoFirstFrame}]" keyName="url"
					:autoplay="false"></uv-swiper>
			</view>
		</view>

		<view v-if="item.data && item.data[0].revised_prompt" 
			style="max-width: 600px;display: flex;justify-content: space-between;align-items: center;flex-wrap: wrap;width: 100%;margin-top: 5px;">
			<view v-for="(ites,ind) in  item.data" :key="JSON.stringify(ites)"
				style="position: relative;max-width: 49%; height: auto;top: 0px;margin-top: 10px;"
				@mouseenter="hoverIndex = ind" @mouseleave="hoverIndex = -1">
				<el-image style="border-radius: 5px;overflow: hidden;" :src="item.data[ind].url+saveImg" fit="fill"
					:preview-src-list="[item.data[ind].url]"></el-image>
				<view v-if="hoverIndex ==ind" style="opacity: 0.8; position: absolute;top:10px;left:10px;">
					<el-tooltip class="item" effect="dark" :content="tooltip" placement="top-start">
						<uv-button @click="download(item.data[ind].url)" type="primary" size="small"
							:text="'下载v'+(ind+1)"
							customStyle="margin-top: 0px;padding: 0px;border-radius: 5px;font-size: 14px;"></uv-button>
					</el-tooltip>
				</view>
			</view>
		</view>
		<view v-if="(imageUrl||imageEndUrl) && (musicShow ||!item.videoUrl)"
			style="display: flex;justify-content: space-between;align-items: center;margin-top: 5px;">
			<el-image v-if="imageUrl" style="max-width:250px; height: auto;" :src="imageUrl+saveImg" fit="fill"
				:preview-src-list="[imageUrl]"></el-image>
			<el-image v-if="imageEndUrl" style="max-width:250px; height: auto;" :src="imageEndUrl+saveImg" fit="fill"
				:preview-src-list="[imageEndUrl]"></el-image>
		</view>
		<view v-if="item.targetImage&&item.swapImage">
			<view style="display: flex;justify-content: space-between;align-items: center;width: 100%;margin: 5px 0px;">
				<el-image v-if="item.targetImage" style="width: 49%; height: auto;" :src="item.targetImage+saveImg"
					fit="fill" :preview-src-list="[item.targetImage]"></el-image>
				<el-image v-if="item.swapImage" style="width: 49%; height: auto;" :src="item.swapImage+saveImg"
					fit="fill" :preview-src-list="[item.swapImage]"></el-image>
			</view>
		</view>
		<el-image v-if="(item.cdnImage||item.discordImage)&&!item.images" style="max-width:250px; height: auto;"
			:src="item.cdnImage+saveImg" fit="fill" :preview-src-list="[item.cdnImage]">
			<div slot="error" class="image-slot">
				<el-image v-if="item.discordImage+saveImg" style="max-width:250px; height: auto;"
					:src="item.discordImage" fit="fill" :preview-src-list="[item.discordImage]">
				</el-image>
			</div>
		</el-image>
		<view
			style="max-width: 600px;display: flex;justify-content: space-between;align-items: center;flex-wrap: wrap;width: 100%;margin-top: 5px;">
			<view v-for="(ites,index) in  item.images" :key="JSON.stringify(ites)"
				style="position: relative;max-width: 48%; height: auto;top: 0px;margin-top: 10px;"
				@mouseenter="hoverIndex = index" @mouseleave="hoverIndex = -1">
				<el-image style="width: 100%;height: 100%;border-radius: 5px;overflow: hidden;" :src="ites+saveImg"
					fit="fill" :preview-src-list="[ites]">
				</el-image>
				<view v-if="hoverIndex ==index" style="opacity: 0.8; position: absolute;top:10px;left:10px;">
					<el-tooltip class="item" effect="dark" :content="tooltip" placement="top-start">
						<uv-button @click="download(ites)" type="primary" size="small" :text="'下载v'+(index+1)"
							customStyle="margin-top: 0px;padding: 0px;border-radius: 5px;font-size: 14px;"></uv-button>
					</el-tooltip>
				</view>
			</view>
		</view>

		<view class="sdadsad" style="display: flex;justify-content: space-between;align-items: center;">
			<el-tooltip v-if="item.role!='user'" class="item" effect="dark" content="复制文字" placement="top-start">
				<el-link
					style="font-size: 14px; color:#8E949C;margin-right: 10px;display: flex;justify-content: flex-start;align-items: center;"
					@click="copy(item.content||item.text||item.revised_prompt||item.userPrompt ||item.prompt)">
					<i style="margin-right: 3px;" class="el-icon-document-copy"></i>
					复制
				</el-link>
			</el-tooltip>
			<el-tooltip v-if="item.role!='user'" class="item" effect="dark" :content="tooltip" placement="top-start">
				<el-link v-if="item.videoUrl || imageUrl"
					style="font-size: 14px; color:#8E949C;margin-right: 0px;display: flex;justify-content: flex-start;align-items: center;"
					@click="download(item.videoUrl ||imageUrl)">
					<i style="margin-right: 0px;" class="el-icon-download"></i>
					下载<i style="margin-left: 3px;color:#000" class="el-icon-info"></i>
				</el-link>
			</el-tooltip>
			<el-tooltip v-if="type !='chat' && taskid"
				style="font-size: 14px;display: flex;justify-content: flex-start;align-items: center;" effect="dark"
				content="分享到首页" placement="top-start">
				<el-link v-if="item.quota" @click="routed('/pages/fusion/index?id='+taskid)">
					<view v-if="show!=2">
						分享
					</view>
					<view v-else>
						取消分享
					</view>
				</el-link>

				<!-- <el-popover placement="top" width="160" v-model="visible">
					<p>确定要取消分享吗？</p>
					<div style="text-align: right; margin: 0">
						<el-button size="mini" type="text" @click="visible = false">取消</el-button>
						<el-button type="primary" size="mini" @click="release()">确定</el-button>
					</div>
					<el-link slot="reference" style="color:#8E949C;">取消分享</el-link>
				</el-popover> -->
			</el-tooltip>
			<el-tooltip v-if="item.quota" class="item" effect="dark" :content="'消耗的'+coin+'，0.00 表示消耗非常小，不是没有消耗'"
				placement="top-start">
				<el-link
					style="font-size: 14px; color:#8E949C;display: flex;justify-content: center;align-items: center;">
					<el-image style="width: 20px; height: auto;margin-bottom: -4px;" :src="image"
						fit="fill"></el-image>{{$uv.priceFormat(item.quota,2)}}
				</el-link>
			</el-tooltip>
		</view>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script>
	// 引入
	import config from '@/common/config'
	import target from '@/components/target/target.vue';
	import {
		download,
		encrypt,
		decrypt,
	} from '@/common/fun.js';
	import {
		userName,
		getUserName
	} from '@/common/api.js';
	export default {
		components: {
			// 注册组件
			target
		},
		props: {
			taskid: String,
			item: Object,
			index: Number,
			type: String,
			aiType: String,
			shows: {
				type: Number,
				default: 0
			},
		},
		data() {
			return {
				fill: config.fill,
				tabbar: config.tabbar,
				visible: false,
				adjustColumn: null,
				hoverIndex: -1,
				show: this.shows,
				musicShow: false,
				image: config.img,
				tooltip: '图片、视频、音乐等在有效期限制，请尽快下载',
			}
		},
		watch: {
			// 监听data数据的变化
			item: {
				handler: function(newVal, oldVal) {
					// console.log(newVal);
					this.show = this.shows;
				},
				deep: true
			},
		},
		computed: {
			saveImg() {
				let path, encryptData = {
					id: this.vuex_user._id
				};
				if (this.type) {
					encryptData['type'] = this.type;
				}
				if (this.aiType) {
					encryptData['api'] = this.aiType;
				}
				if (this.taskid) {
					encryptData['taskid'] = this.taskid;
				}

				if (this.vuex_token) {
					path = '?encrypt=' + encodeURIComponent(encrypt(encryptData, this.aes_decrypt(this.vuex_token))) +
						'&token=' + this
						.aes_decrypt(this.vuex_token);
				}
				return (this.vuex_token && this.vuex_user && this.vuex_user._id) ? path : '';
			},
			imageUrl() {
				return this.item.url || this.item.imageUrl || '';
			},
			imageEndUrl() {
				return this.item.imageEndUrl;
			},
			extractImageUrls() { // 主函数：从任意结构中提取图片 URL
				var that = this;
				const results = new Set(); // 使用 Set 自动去重
				const visited = new WeakSet(); // 防止循环引用
				// 递归遍历函数
				function traverse(obj) {
					if (!obj || visited.has(obj)) return;
					// 标记已访问对象（避免循环引用）
					if (typeof obj === 'object' && obj !== null) {
						visited.add(obj);
					}
					// 处理字符串（核心匹配逻辑）
					if (typeof obj === 'string') {
						if (that.isImageUrl(obj)) {
							results.add(obj);
						}
						return;
					}
					// 处理数组
					if (Array.isArray(obj)) {
						obj.forEach(item => traverse(item));
						return;
					}
					// 处理对象
					if (typeof obj === 'object') {
						Object.values(obj).forEach(itm => traverse(itm));
					}
				}
				traverse(this.item);
				return Array.from(results); // 转为数组返回
			},
		},
		mounted() {
			this.adjustColumnCount();
		},
		created() {
			uni.onWindowResize(this.adjustColumnCount);
		},
		methods: {
			download,
			// 判断字符串是否为图片 URL
			isImageUrl(str) {
				// 匹配图片扩展名 // 匹配完整图片 URL // 匹配 base64 图片
				return /\.(jpe?g|png|gif|bmp|webp|svg)(\?[^\\s]*)?$/i.test(str) ||
					/^(https?:\/\/.*\.(?:png|jpg|jpeg|gif|webp))/i.test(str) || /^data:image\/([a-zA-Z]*);base64,/.test(
						str);
			},
			substring(str) {
				// 匹配常见URL模式的正则表达式（包括无协议和含参数的URL）
				const urlRegex = /((?:https?|ftp):\/\/|\bwww\.)[^\s/$.?#][^\s]*|([a-z0-9.-]+\.[a-z]{2,}\/?[^\s]*)/gi;
				str = str.replace(urlRegex, '').trim();
				let strdd = str.split(',')[0];
				return strdd.split('，')[0];
			},
			tagNormalizer(e) {
				return e.map(tag => {
					if (typeof tag === 'string') return tag.trim().toLowerCase();
					if (tag.toString) return tag.toString().trim().toLowerCase();
					return '';
				})
			},
			async release() {
				if (this.taskid) {
					await userName('flow', {
						id: this.taskid,
					}, {
						custom: {
							auth: true,
							toast: true,
						},
					}).then(e => {
						// console.log(e);
						this.$refs.toast.show({
							message: e == 2 ? '分享成功！' : '关闭分享！',
						});
						this.show = e;
						this.visible = false;
						this.$uv.vuex('dsgesfv', this.taskid);
					}).catch(e => {
						console.log(e);
					})
				} else {
					console.log(this.taskid);
				}
			},
			adjustColumnCount() {
				var that = this;
				const query = uni.createSelectorQuery().in(this);
				query.select('.sdadsad').boundingClientRect(data => {
					if (data) {
						that.adjustColumn = data;
						// console.log(data);
					}
				}).exec();
			},
			del(index) {
				this.$emit('del-event', index);
			},
			replaced(text) {
				if (!text) return;
				if (typeof text !== 'string') {
					text = text[0].text
				}
				const msgs = text.split(' --');
				if (typeof msgs != 'string') {
					text = msgs[0];
				}
				if (msgs[0].includes('http')) {
					var arr = msgs[0].split(' ');
					text = msgs[0].replace(arr[0] + ' ', '');
				} else {
					text = msgs[0];
				}
				// 安全处理HTML标签，防止XSS
				const escapeHTML = (str) => {
					return str
						.replace(/&/g, '&amp;')
						.replace(/</g, '&lt;')
						.replace(/>/g, '&gt;')
						.replace(/"/g, '&quot;')
						.replace(/'/g, '&#039;');
				};


				text = text.replace(/(```[\s\S]*?```)/g, '<pre class="code-block">$1</pre>');
				text = text.replace(/(```\b\w+\b)/g,
					'<div class="copy-text"><span style="font-weight: bold;font-size: 15px;color:#ababab">$1</span>复制</div>'
				);
				text = text.replace(/```/g, '');
				text = text.replace(/(###[\s\S]*?\\n)/g,
					'<span style="font-weight: bold;color:#00000">$1</span>'
				);
				text = text.replace(/(###[\s\S]*?\n)/g,
					'<span style="font-weight: bold;color:#00000">$1</span>'
				);
				text = text.replace(/###/g, '');
				text = text.replace(/\\n/g, "<br>");
				text = text.replace(/\n/g, "<br>");
				text = text.replace(/<article[^>]*>/g, '<p>').replace(/<section[^>]*>/g, '<p>');
				// text && text.replace(/(\s{2,})(?![^<>]*>)/g, function(
				// 	match) {
				// 	return match.replace(/ /g, '&nbsp;');
				// });

				// 识别LoRA标签并替换为带样式的span
				const loraRegex = /<lora:([^:]+):([^>]+)>/g;
				return text.replace(loraRegex, (match, modelName, weight) => {
					return `<span class="lora-tag" title="LoRA模型: ${modelName}, 权重: ${weight}">
				              <span class="lora-label">LoRA</span>:${modelName}:${weight}
				            </span>`;
				});
				text = escapeHTML(text); // 先转义所有HTML标签
				console.log(text);
				return text;
			},
			copyCode(text) {
				var that = this;
				const target = event.target;
				const classList = target.classList;
				if (classList && classList.contains('copy-text')) {
					const clas = target.parentNode;
					let first = {};
					if (clas.firstChild) {
						first = clas.firstChild;
						clas.removeChild(clas.firstChild);
					}
					let text = clas.innerText;
					if (first) {
						clas.prepend(first);
					}
					// const text = target.getAttribute('data-text');
					// console.log(text);
					that.copy(text);
				}
			},
			copy(text) {
				var that = this;
				if (typeof text !== 'string') {
					text = text[0].text
				}
				text = text.replace(/```/g, '');
				text = text.replace(/###/g, '');
				uni.setClipboardData({
					data: text,
					success: function() {
						that.$refs.toast.show({
							message: "复制成功"
						})
					},
					complete: function() {
						uni.hideToast();
					}
				});
			},
			routed(url) {
				uni.$uv.route({
					url: url,
					// intercept(params, next) {
					// 	console.log(params, next)
					// 	uni.showLoading({
					// 		title: '等待中...'
					// 	})
					// 	// 模拟处理等待
					// 	setTimeout(() => {
					// 		uni.hideLoading();
					// 		next(true);
					// 	}, 1000)
					// }
				})
			}
		}
	}
</script>
<style scoped lang="scss">
	.item_content {
		max-width: 600px;
		overflow: hidden;
		background-color: #65dee2;
		height: auto;
		background-color: #fff;
		// margin-right: 10px;
		// padding: 6px;
		// width: calc(100vw-60px);
	}

	/* 加载前 */
	::v-deep .el-image__placeholder {
		min-width: 120px;
		min-height: 120px;
		background: url('@/static/loading.gif') no-repeat 50% 50% !important;
		background-size: 50% !important;
	}


	.selectable-text {
		overflow: hidden;
		-webkit-user-select: text;
		/* Safari */
		-moz-user-select: text;
		/* Firefox */
		-ms-user-select: text;
		/* IE 10+ */
		user-select: text;
		/* Standard syntax */

		.copy-text {
			display: flex;
			justify-content: space-between;
		}

		.copy-text:hover {
			color: #409EFF;
			cursor: pointer;
		}

		.code-block {
			background-color: #f8f8f8;
			border: 1px solid #ddd;
			padding: 10px;
			margin: 10px 0;
			white-space: pre-wrap;
			word-break: break-all;
			font-family: 'Courier New', Courier, monospace;
			font-size: 14px;
		}

		.lora-tag {
			background-color: rgba(128, 0, 128, 0.1);
			color: #800080;
			padding: 2px 4px;
			border-radius: 3px;
			margin: 0 2px;
			white-space: nowrap;
			font-size: 0.9em;
		}

		.lora-label {
			font-weight: bold;
			margin-right: 2px;
		}

		.positive-prompt,
		.negative-prompt {
			padding: 10px;
			border-radius: 5px;
			margin-bottom: 15px;
			white-space: pre-wrap;
		}

		.positive-prompt {
			background-color: rgba(0, 128, 0, 0.05);
			border-left: 3px solid #008000;
		}

		.negative-prompt {
			background-color: rgba(128, 0, 0, 0.05);
			border-left: 3px solid #800000;
		}
	}
</style>